{% extends "base.html" %}

{% block content %}
<div class="flex h-[calc(100vh-140px)]">
    <div class="w-80 bg-white border-r border-gray-200 flex flex-col">
        <div class="p-4 border-b border-gray-200">
            <button 
                onclick="startNewChat()"
                class="w-full bg-indigo-600 text-white py-2 px-4 rounded-lg hover:bg-indigo-700 flex items-center justify-center space-x-2"
            >
                <i class="fas fa-plus"></i>
                <span>New Chat</span>
            </button>
        </div>
        
        <div class="flex-1 overflow-y-auto p-4">
            <div class="space-y-2" id="chatHistory">
                <p class="text-sm text-gray-500 text-center py-4">No chat history</p>
            </div>
        </div>
    </div>

    <div class="flex-1 flex flex-col">
        <div class="border-b border-gray-200 p-4">
            <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-600">Filter by Collection:</span>
                <div class="flex flex-wrap gap-2" id="collectionFilters">
                    <button onclick="setCollectionFilter(null)" class="collection-filter px-3 py-1 bg-indigo-100 text-indigo-800 rounded-full text-sm font-medium">
                        All Documents
                    </button>
                </div>
            </div>
        </div>

        <div class="flex-1 overflow-y-auto p-6 space-y-6" id="messagesContainer">
            <div class="max-w-3xl mx-auto text-center py-12">
                <i class="fas fa-comments text-gray-300 text-6xl mb-4"></i>
                <h3 class="text-xl font-semibold text-gray-900 mb-2">Medical Device Regulatory Assistant</h3>
                <p class="text-gray-600">Ask questions about medical device regulations, compliance requirements, and regulatory standards.</p>
            </div>
        </div>

        <div class="border-t border-gray-200 p-4">
            <div class="max-w-4xl mx-auto">
                <div class="flex flex-wrap gap-2 mb-3">
                    <button onclick="setQuickPrompt(this)" class="px-3 py-1.5 bg-gray-100 text-gray-700 rounded-lg text-sm hover:bg-gray-200">
                        What tests are needed for 510(k)?
                    </button>
                    <button onclick="setQuickPrompt(this)" class="px-3 py-1.5 bg-gray-100 text-gray-700 rounded-lg text-sm hover:bg-gray-200">
                        Summarize ISO 13485 requirements
                    </button>
                    <button onclick="setQuickPrompt(this)" class="px-3 py-1.5 bg-gray-100 text-gray-700 rounded-lg text-sm hover:bg-gray-200">
                        NMPA Class II timeline
                    </button>
                </div>
                
                <form id="chatForm" onsubmit="sendMessage(event)" class="relative">
                    <input 
                        type="text" 
                        id="chatInput"
                        placeholder="Ask a question about medical device regulations..."
                        class="w-full pl-4 pr-12 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    >
                    <button 
                        type="submit"
                        class="absolute right-2 top-1/2 transform -translate-y-1/2 bg-indigo-600 text-white p-2 rounded-lg hover:bg-indigo-700"
                    >
                        <i class="fas fa-paper-plane"></i>
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/9.1.6/marked.min.js"></script>
<script>
let currentSessionId = null;
let currentCollectionFilter = null;
let allCollections = [];

marked.setOptions({
    breaks: true,
    gfm: true,
    headerIds: false,
    mangle: false
});

document.addEventListener('DOMContentLoaded', async () => {
    await loadCollections();
});

async function loadCollections() {
    try {
        const response = await fetch('/api/collections/list');
        const data = await response.json();
        if (data.status === 'success') {
            allCollections = data.collections;
            renderCollectionFilters();
        }
    } catch (error) {
        console.error('Error loading collections:', error);
    }
}

function renderCollectionFilters() {
    const container = document.getElementById('collectionFilters');
    container.innerHTML = `
        <button onclick="setCollectionFilter(null)" class="collection-filter px-3 py-1 bg-indigo-100 text-indigo-800 rounded-full text-sm font-medium">
            All Documents
        </button>
    `;
    
    allCollections.forEach(collection => {
        const button = document.createElement('button');
        button.onclick = () => setCollectionFilter(collection.name);
        button.className = 'collection-filter px-3 py-1 bg-gray-100 text-gray-800 rounded-full text-sm font-medium hover:bg-gray-200';
        button.textContent = collection.display_name || collection.name;
        container.appendChild(button);
    });
}

function setCollectionFilter(collection) {
    currentCollectionFilter = collection;
    
    document.querySelectorAll('.collection-filter').forEach(btn => {
        btn.classList.remove('bg-indigo-100', 'text-indigo-800');
        btn.classList.add('bg-gray-100', 'text-gray-800');
    });
    
    event.target.classList.add('bg-indigo-100', 'text-indigo-800');
    event.target.classList.remove('bg-gray-100', 'text-gray-800');
}

function startNewChat() {
    currentSessionId = null;
    document.getElementById('messagesContainer').innerHTML = `
        <div class="max-w-3xl mx-auto text-center py-12">
            <i class="fas fa-comments text-gray-300 text-6xl mb-4"></i>
            <h3 class="text-xl font-semibold text-gray-900 mb-2">Medical Device Regulatory Assistant</h3>
            <p class="text-gray-600">Ask questions about medical device regulations, compliance requirements, and regulatory standards.</p>
        </div>
    `;
    document.getElementById('chatInput').value = '';
    document.getElementById('chatInput').focus();
}

function setQuickPrompt(button) {
    document.getElementById('chatInput').value = button.textContent.trim();
    document.getElementById('chatInput').focus();
}

function openDocumentViewer(docId) {
    window.open(`/view/${docId}`, '_blank');
}

async function sendMessage(event) {
    event.preventDefault();
    
    const input = document.getElementById('chatInput');
    const question = input.value.trim();
    
    if (!question) return;
    
    const container = document.getElementById('messagesContainer');
    if (container.querySelector('.text-center.py-12')) {
        container.innerHTML = '';
    }
    
    addMessageToUI('user', question);
    input.value = '';
    
    addLoadingMessage();
    
    try {
        const response = await fetch('/api/chat/ask', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                question: question,
                session_id: currentSessionId,
                collection_filter: currentCollectionFilter
            })
        });
        
        const data = await response.json();
        
        removeLoadingMessage();
        
        if (data.status === 'success') {
            currentSessionId = data.result.session_id;
            addAssistantMessageToUI(data.result.answer);
        } else {
            throw new Error(data.message);
        }
    } catch (error) {
        removeLoadingMessage();
        addMessageToUI('error', 'Sorry, there was an error processing your question. Please try again.');
    }
}

function addMessageToUI(role, content) {
    const container = document.getElementById('messagesContainer');
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `max-w-3xl mx-auto ${role === 'user' ? '' : 'ml-11'}`;
    
    if (role === 'user') {
        messageDiv.innerHTML = `
            <div class="flex items-start space-x-3">
                <div class="w-8 h-8 bg-indigo-600 rounded-full flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-user text-white text-sm"></i>
                </div>
                <div class="bg-white border border-gray-200 rounded-lg p-4 flex-1">
                    <p class="text-gray-900">${escapeHtml(content)}</p>
                </div>
            </div>
        `;
    } else if (role === 'error') {
        messageDiv.innerHTML = `
            <div class="bg-red-50 border border-red-200 rounded-lg p-4">
                <p class="text-red-800">${escapeHtml(content)}</p>
            </div>
        `;
    }
    
    container.appendChild(messageDiv);
    container.scrollTop = container.scrollHeight;
}

function addLoadingMessage() {
    const container = document.getElementById('messagesContainer');
    
    const loadingDiv = document.createElement('div');
    loadingDiv.id = 'loadingMessage';
    loadingDiv.className = 'max-w-3xl mx-auto ml-11';
    loadingDiv.innerHTML = `
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div class="flex items-center space-x-2">
                <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-indigo-600"></div>
                <p class="text-gray-700">Analyzing regulations...</p>
            </div>
        </div>
    `;
    
    container.appendChild(loadingDiv);
    container.scrollTop = container.scrollHeight;
}

function removeLoadingMessage() {
    const loadingMsg = document.getElementById('loadingMessage');
    if (loadingMsg) {
        loadingMsg.remove();
    }
}

function addAssistantMessageToUI(answer) {
    const container = document.getElementById('messagesContainer');
    
    const messageDiv = document.createElement('div');
    messageDiv.className = 'max-w-3xl mx-auto ml-11';
    
    // Render citations with clickable document links
    let citationsHTML = '';
    if (answer.citations && answer.citations.length > 0) {
        const citationsList = answer.citations.map((citation, index) => {
            return `<button onclick="openDocumentViewer('${citation.document_id}')" 
                    class="citation-chip px-3 py-1.5 bg-blue-100 text-blue-700 rounded-lg text-sm hover:bg-blue-200 transition-colors flex items-center space-x-1">
                    <i class="fas fa-file-alt text-xs"></i>
                    <span>[${index + 1}] ${escapeHtml(citation.document_name)}</span>
                </button>`;
        }).join(' ');
        citationsHTML = `
            <div class="mb-3">
                <p class="text-xs font-medium text-gray-600 mb-2">Referenced Documents:</p>
                <div class="flex flex-wrap gap-2">${citationsList}</div>
            </div>
        `;
    }
    
    // Render regulatory basis
    const regulatoryBasis = answer.regulatory_basis !== 'No relevant regulation found in knowledge base' 
        ? `<div class="mb-3 p-3 bg-indigo-50 border border-indigo-100 rounded-lg text-sm">
            <p class="font-semibold text-indigo-900 mb-1">Regulatory Basis:</p>
            <p class="text-indigo-700">${escapeHtml(answer.regulatory_basis)}</p>
           </div>`
        : '';
    
    // Render the detailed analysis with markdown
    const renderedAnalysis = marked.parse(answer.detailed_analysis || '');
    
    messageDiv.innerHTML = `
        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            ${regulatoryBasis}
            ${citationsHTML}
            <div class="text-gray-900 mb-3 prose prose-sm max-w-none">${renderedAnalysis}</div>
            <div class="flex items-center space-x-4 pt-3 border-t border-blue-200">
                <button class="flex items-center space-x-1 text-sm text-gray-600 hover:text-gray-800">
                    <i class="fas fa-thumbs-up"></i>
                    <span>Helpful</span>
                </button>
                <button class="flex items-center space-x-1 text-sm text-gray-600 hover:text-gray-800">
                    <i class="fas fa-thumbs-down"></i>
                    <span>Not helpful</span>
                </button>
                <button class="flex items-center space-x-1 text-sm text-gray-600 hover:text-gray-800">
                    <i class="fas fa-flag"></i>
                    <span>Flag outdated</span>
                </button>
            </div>
        </div>
    `;
    
    container.appendChild(messageDiv);
    container.scrollTop = container.scrollHeight;
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

document.getElementById('chatInput').addEventListener('keypress', function(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        document.getElementById('chatForm').dispatchEvent(new Event('submit'));
    }
});
</script>

<style>
.prose p {
    margin-bottom: 0.75rem;
}

.prose ul, .prose ol {
    margin-left: 1.5rem;
    margin-bottom: 0.75rem;
}

.prose li {
    margin-bottom: 0.25rem;
}

.prose strong {
    font-weight: 600;
    color: #1f2937;
}

.prose code {
    background-color: #f3f4f6;
    padding: 0.125rem 0.25rem;
    border-radius: 0.25rem;
    font-size: 0.875em;
}

.prose h1, .prose h2, .prose h3 {
    font-weight: 600;
    margin-top: 1rem;
    margin-bottom: 0.5rem;
}

.citation-chip {
    display: inline-flex;
}
</style>
{% endblock %}